(function ($) {
    "use strict";

    var defaultOpt = {
        gridFit: true,
        loader: $.EasyUiLoader,
        pagination: true,
        view: {
            grid: "",
            myToolbar: "",
            colbar: ""
        },
        configs: {
            gridTitle: "",
            gridUrl: "",
            colUrl: "",
            onBeforeLoad: $.noop,
            gridColumns: [],
            onLoadSuccess: $.noop,
            onCheck: $.noop,
            onUncheck: $.noop,
            onCheckAll: $.noop,
            onUncheckAll: $.noop
        },
        events: {
            renderColBarBefore: $.noop,
            renderTableRow: $.noop,
            onClickColBtn: $.noop,
            onClickToolbarBtn: $.noop
        }
    };

    var defaultTreeOpt = {
        gridFit: true,
        loader: $.EasyUiLoader,
        pagination: true,
        view: {
            grid: "",
            myToolbar: "",
            colbar: ""
        },
        configs: {
            gridTitle: "",
            gridUrl: "",
            idField: 'id',
            treeField: 'name',
            colUrl: "",
            onBeforeLoad: $.noop,
            gridColumns: [],
            queryParams:{},
            onLoadSuccess: $.noop,
            onCheck: $.noop,
            onUncheck: $.noop,
            onCheckAll: $.noop,
            onUncheckAll: $.noop,
            onExpand: $.noop
        },
        events: {
            renderColBarBefore: $.noop,
            renderTableRow: $.noop,
            onClickColBtn: $.noop,
            onClickToolbarBtn: $.noop
        }
    };
    var templates = {
        normalViewTemplate: '<table border="0" cellpadding="0" cellspacing="0" class="hydra-table">{{#.}}' +
            '<tr class="hydra-tr-bg"><td class="hydra-left">{{title}}：</td><td class="hydra-right">{{&value}}</td></tr>{{/.}}</table>'
    };

    function sortNumber(a, b) {
        return a.sort - b.sort;
    }

    function PageListComponent(uuid, opt) {
        if (!uuid) {
            return;
        }
        this.opt = $.extend({autoload: true}, defaultOpt, opt);
        var that = this;
        var page = new $.PageDomFactory(uuid);
        this.pageContext = page;
        this.templates = templates;
        this.grid = page.getJqDom(that.opt.view.grid);
        this.myToolbar = page.getJqDom(that.opt.view.myToolbar);
        var colbar = page.getJqDom(that.opt.view.colbar).hide();
        colbar.find("[data-key]").each(function (i, item) {
            $(this).attr("title", $(this).html());
            $(this).empty();
        });
        var columns = that.opt.configs.gridColumns;
        this.hColumns = columns.slice(0);
        if (that.opt.view.colbar) {
            columns.push({
                field: 'available1',
                title: '操作',
                width: 110,
                align: 'center',
                formatter: function (value, row, index) {
                    var a = [];
                    colbar.find("[data-key]").each(function (i, item) {
                        var fc = that.opt.events.renderColBarBefore;
                        if (!fc || that.opt.events.renderColBarBefore.call(that, $(this).attr("data-key"), row)) {
                            a.push(Mustache.render(this.outerHTML, row))
                        }
                    });
                    return a.join("");
                }
            })
        }

        function renderColbar(){
            var panel = $(this).datagrid("getPanel");
            panel.find(".datagrid-view2").find("[data-key]").not(".l-btn").each(function (i, item) {
                var target = $(item).attr("data-target"), _href = $(item).attr("data-href") + ($(this).attr("data-param") || "");
                $(item).attr("href", "javascript:void(0)");
                if (target == 'link') {
                    $(item).attr("href", _href);
                }
            }).linkbutton({
                plain: true,
                onClick: function () {
                    var id = $(this).attr("data-id"),
                        key = $(this).attr("data-key"),
                        href = $(this).attr("data-href") + ($(this).attr("data-param") || ""),
                        target = $(this).attr("data-target");
                    var current,
                        rows = that.grid.datagrid("getRows");
                    A:for (var i = 0; i < rows.length; i++) {
                        B:for (var j in rows[i]) {
                            if (id == rows[i][j]) {
                                current = rows[i];
                                break A;
                            }
                        }
                    }
                    if (current && that.opt.events.onClickColBtn) {
                        that.opt.events.onClickColBtn.call(this, that, {
                            key: key,
                            href: href,
                            target: target
                        }, current);
                    }
                }
            });
        }

        var gridOp = {
//                    title: that.opt.configs.gridTitle,
            url: that.opt.configs.gridUrl,
            queryParams: that.opt.configs.queryParams,
            toolbar: that.myToolbar,
            border: false,
            fitColumns: true,
            pagination: that.opt.pagination,
            checkOnSelect: true,
            selectOnCheck: true,
            singleSelect: that.opt.configs.singleSelect || false,
            rownumbers: true,
            pageList: [10, 20, 30, 50],
            fit: that.opt.gridFit,
            onBeforeLoad: that.opt.configs.onBeforeLoad,
            onUpdateSuccess:function(row){
                renderColbar.call(this);
            },
            onLoadSuccess: function (grid) {
                var panel = $(this).datagrid("getPanel");
                if (that.opt.events.renderTableRow) {
                    panel.find(".datagrid-view2 [datagrid-row-index]").each(function (index, item) {
                        var data = grid.rows;
                        for (var i = 0; i < data.length; i++) {
                            if (index == i) {
                                that.opt.events.renderTableRow(index, item, data[i]);
                            }
                        }
                    });
                }
                renderColbar.call(this, grid);
                if (that.opt.configs.onLoadSuccess) {
                    that.opt.configs.onLoadSuccess(grid);
                }
            },
            onCheck: that.opt.configs.onCheck,
            onUncheck: that.opt.configs.onUncheck,
            onCheckAll: that.opt.configs.onCheckAll,
            onUncheckAll: that.opt.configs.onUncheckAll,
            onBeforeSelect:function(){
                return false;
            },
            loader: that.opt.loader,
            columns: [
                columns
            ]
        };
        that.grid.datagrid(gridOp);
        $("#globContent").on("resize", function () {
            that.grid.datagrid('resize');
        });
        this.myToolbar.find("[data-key]").each(function (i, item) {
            var target = $(item).attr("data-target"), _href = $(item).attr("data-href");
            $(item).attr("href", "javascript:void(0)");
            if (target == 'link') {
                $(item).attr("href", _href);
            }
        }).linkbutton({
            plain: true,
            onClick: function () {
                var key = $(this).attr("data-key"), href = $(this).attr("data-href");
                var target = $(this).attr("data-target");
                that.opt.events.onClickToolbarBtn.call(this, that, {
                    key: key,
                    href: href,
                    target: target
                })
            }
        })
    }

    function PageTreeListComponent(uuid, opt) {
        if (!uuid) {
            return;
        }
        this.opt = $.extend({autoload: true}, defaultTreeOpt, opt);
        var that = this;
        var page = new $.PageDomFactory(uuid);
        this.pageContext = page;
        this.templates = templates;
        this.grid = page.getJqDom(that.opt.view.grid);
        this.myToolbar = page.getJqDom(that.opt.view.myToolbar);
        var colbar = page.getJqDom(that.opt.view.colbar).hide();
        colbar.find("[data-key]").each(function (i, item) {
            $(this).attr("title", $(this).html());
            $(this).empty();
        });
        var columns = that.opt.configs.gridColumns;
        this.hColumns = columns.slice(0);
        if (that.opt.view.colbar) {
            columns.push({
                field: 'available1',
                title: '操作',
                width: 110,
                align: 'center',
                formatter: function (value, row, index) {
                    var a = [];
                    colbar.find("[data-key]").each(function (i, item) {
                        var fc = that.opt.events.renderColBarBefore;
                        if (!fc || that.opt.events.renderColBarBefore.call(that, $(this).attr("data-key"), row)) {
                            a.push(Mustache.render(this.outerHTML, row))
                        }
                    });
                    return a.join("");
                }
            })
        }
        function renderColbar(){
            var panel = $(this).datagrid("getPanel");
            panel.find(".datagrid-view2").find("[data-key]").not(".l-btn").each(function (i, item) {
                var target = $(item).attr("data-target"), _href = $(item).attr("data-href") + ($(this).attr("data-param") || "");
                $(item).attr("href", "javascript:void(0)");
                if (target == 'link') {
                    $(item).attr("href", _href);
                }
            }).linkbutton({
                plain: true,
                onClick: function () {
                    var id = $(this).attr("data-id");
                    var key = $(this).attr("data-key"), href = $(this).attr("data-href") + ($(this).attr("data-param") || "");
                    var target = $(this).attr("data-target");
                    var current = that.grid.treegrid("find", id);
                    if (current && that.opt.events.onClickColBtn) {
                        that.opt.events.onClickColBtn.call(this, that, {
                            key: key,
                            href: href,
                            target: target
                        }, current);
                    }
                }
            });
        }
        var gridOp = {
//                    title: that.opt.configs.gridTitle,
            url: that.opt.configs.gridUrl,
            toolbar: that.myToolbar,
            border: false,
            fitColumns: true,
            queryParams:that.opt.configs.queryParams,
            animate: false,
            idField: that.opt.configs.idField,//id=productId_propId_largetypeId_midlletypeId_comtypeId;
            treeField: that.opt.configs.treeField,
            pagination: that.opt.pagination,
            checkOnSelect: true,
            selectOnCheck: true,
            singleSelect: false,
            rownumbers: true,
            pageList: [5, 10, 15],
            fit: that.opt.gridFit,
            onBeforeLoad: that.opt.configs.onBeforeLoad,
            onCheck: that.opt.configs.onCheck,
            onUncheck: that.opt.configs.onUncheck,
            onCheckAll: that.opt.configs.onCheckAll,
            onUncheckAll: that.opt.configs.onUncheckAll,
            onExpand: that.opt.configs.onExpand,
            onUpdateSuccess:function(row){
                renderColbar.call(this);
            },
            onBeforeSelect:function(){
                return false;
            },
            onLoadSuccess: function (grid) {
                that.grid.treegrid("collapseAll");
                var panel = $(this).datagrid("getPanel");
                if (that.opt.events.renderTableRow) {
                    panel.find(".datagrid-view2 [datagrid-row-index]").each(function (index, item) {
                        var data = that.grid.treegrid("getData");
                        for (var i = 0; i < data.length; i++) {
                            if (index == i) {
                                that.opt.events.renderTableRow(index, item, data[i]);
                            }
                        }
                    });
                }
                renderColbar.call(this);
                if (that.opt.configs.onLoadSuccess) {
                    that.opt.configs.onLoadSuccess(grid);
                }
            },
            loader: that.opt.loader,
            columns: [
                columns
            ]
        };
        that.grid.treegrid(gridOp);
        $("#globContent").on("resize", function () {
            that.grid.treegrid('resize');
        });
        this.myToolbar.find("[data-key]").each(function (i, item) {
            var target = $(item).attr("data-target"), _href = $(item).attr("data-href");
            $(item).attr("href", "javascript:void(0)");
            if (target == 'link') {
                $(item).attr("href", _href);
            }
        }).linkbutton({
            plain: true,
            onClick: function () {
                var key = $(this).attr("data-key"), href = $(this).attr("data-href");
                var target = $(this).attr("data-target");
                that.opt.events.onClickToolbarBtn.call(this, that, {
                    key: key,
                    href: href,
                    target: target
                })
            }
        })
    }

    PageTreeListComponent.prototype = new PageListComponent();

    //对常用按钮的封装
    PageListComponent.prototype.searchAll = function () {
        this.grid.datagrid("load", {});
    };

    PageTreeListComponent.prototype.searchAll = function () {
        this.grid.treegrid("load", {});
    };

    PageTreeListComponent.prototype.search = function (href, title, method) {
        if (!this.searchPanel) {
            this.searchPanel = new $.PageWindow();
        }
        var that = this;
        this.searchPanel.create({
            href: href,
            title: title,
            height: 450,
            width: 600,
            buttonOp: {text: "搜索", iconCls: "e-icon fa fa-search fa-lg"},
            method: method,
            callback: function (postData) {
                that.grid.treegrid("reload", $.utils.buildJson(postData));
            },
            doms: {grid: this.grid}
        });
        this.searchPanel.open();
    };

    PageListComponent.prototype.search = function (href, title, method) {
        if (!this.searchPanel) {
            this.searchPanel = new $.PageWindow();
        }
        var that = this;
        this.searchPanel.create({
            href: href,
            title: title,
            height: 450,
            width: 600,
            buttonOp: {text: "搜索", iconCls: "e-icon fa fa-search fa-lg"},
            method: method,
            callback: function (postData) {
                that.grid.datagrid("reload", postData);
            },
            doms: {grid: this.grid}
        });
        this.searchPanel.open();
    };


    PageListComponent.prototype.detail = function (title, row, temp, size, renderAfter) {
        if (!temp) {
            temp = this.templates.normalViewTemplate;
        }
        function getValue(item, key) {
            var keys = key.split(".");
            var it = $.extend({}, item);
            for (var i = 0, l = keys.length; i < l; i++) {
                if (it[keys[i]] == undefined) {
                    return "";
                }
                it = it[keys[i]];
            }
            return it;
        }

        var _size = size || {};
        var config = [];
        for (var i = 0, l = this.hColumns.length; i < l; i++) {
            if (this.hColumns[i].title) {
                var v = this.hColumns[i].field;
                if (this.hColumns[i].formatter) {
                    v = $.utils.createUUID(10);
                    row[v] = this.hColumns[i].formatter(getValue(row, this.hColumns[i].field), row);
                }
                config.push({
                    title: this.hColumns[i].title,
                    value: "{{{" + v + "}}}"
                })
            }
        }
        var htmlTemp = Mustache.render(temp, config);
        var that = this;
        htmlTemp = '<div class="hydra-table-d-wrap">' + Mustache.render(htmlTemp, row) + '</div>';
        if (!this.detailDialog) {
            this.detailDialog = $('<div id="' + $.utils.createUUID(5) + '"></div>').appendTo("body");
            this.detailDialog.html(htmlTemp);
            this.detailDialog.dialog({
                width: _size.width == undefined ? 500 : size.width,
                height: _size.height == undefined ? "auto" : _size.height,
                closed: true,
                modal: true,
                title: title,
                loadingMessage: '',
                buttons: [
                    {
                        text: "关闭",
                        handler: function () {
                            that.detailDialog.dialog("close");
                        }
                    }
                ]
            })
        } else {
            this.detailDialog.html(htmlTemp);
            this.detailDialog.dialog(_size || {})
        }
        if (renderAfter) {
            renderAfter.call(this.detailDialog[0], row);
        }
        this.detailDialog.dialog("hcenter");
        this.detailDialog.dialog("open");
    };
    PageListComponent.prototype.del = function (url, filter) {
        var firstSelected = this.grid.datagrid('getChecked');
        //debugger;
        if (firstSelected.length == 0) {
            $.messager.alert('信息', "请先选择一行!", 'info');
            this.grid.datagrid('clearSelections');
            return;
        }
        var that = this;
        if (firstSelected.length > 0) {
            $.messager.confirm('确定', '确定要删除吗?',
                function (result) {
                    if (result) {
                        var postData = {};
                        if (!filter || !$.isFunction(filter)) {
                            var key = filter || "id";
                            postData.ids = firstSelected.map(function (item) {
                                return item[key];
                            });
                        } else {
                            postData = filter(firstSelected);
                        }

                        $.post(url,
                            $.utils.buildJson(postData),
                            function (json) {
                                if ($.isErrorRequest(json)) {
                                    $.messager.alert('信息', json.msg, 'info');
                                } else {
                                    that.grid.datagrid("reload");
                                    $.messager.alert('信息',
                                        '删除成功', 'info');
                                }
                            });
                    }
                });
        }
    };

    $.PageListComponent = PageListComponent;
    $.PageTreeListComponent = PageTreeListComponent;
})(jQuery);